package com.bree.erp.service.stateless;

import java.util.Collection;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import com.bree.erp.entity.Unit;
import com.bree.erp.service.UnitService;


@Stateless
public class UnitServiceBean implements UnitService {

	@PersistenceContext()
	private EntityManager em;
	
	public UnitServiceBean() {
		
	}
	
	public UnitServiceBean(EntityManager em) {
		this.em = em;
	}
	
	@Override
	public Unit create(String code, String abbreviation, String description) {
		
		Unit unit = new Unit();
		
		unit.setCode(code);
		unit.setAbbreviation(abbreviation);
		unit.setDescription(description);
		
		em.persist(unit);
		
		return unit;
	}

	@Override
	public Unit read(String code) {
		
		return em.find(Unit.class, code);
	}

	@Override
	public Unit update(String code, String abbreviation, String description) {
		
		Unit unit = read(code);
		
		unit.setAbbreviation(abbreviation);
		unit.setDescription(description);
		
		return unit;
	}

	@Override
	public void delete(String code) {
		
		Unit unit = read(code);
		em.remove(unit);
		
	}

	@Override
	public Collection<Unit> list() {
		TypedQuery<Unit> query = em.createNamedQuery(Unit.QUERY_SELECT_ALL_UNIT, Unit.class);
		return query.getResultList();
	}

}
